<?php

namespace App\Services\OpenGroup;

use App\Models\Group;
use App\Models\GroupCard;
use App\Models\User;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;
use Rainsens\Dinglog\Facades\Dinglog;

class OpenGroupRequest extends FormRequest
{
	public function rules()
	{
		
		return [
			'product_id' => [
				'required',
				'integer',
				'min:1',
				$this->product(),
			],
			
		];
	}

	public function product()
	{
		return function ($key, $value, $fail) {


			$product  = Product::find($value);
			$user = request()->user();
			$group = $user->groups()->noFinished()->where('product_id',$value)->first();


			if (!$product) {
				return $fail('此商品不存在');
			}elseif (!$sku = $product->skus()->first()) {
				return $fail('此商品不存在');
			} elseif (!$product->is_sale) {
				return $fail('此商品未上架');
			} elseif (!$product->is_group) {
				return $fail('此商品不是团购商品');
			} elseif (!$product->group_number < 0) {
				return $fail('此商品无法开团');
			} elseif ($sku->stock === 0) {
				return $fail('此商品已售完');
			}elseif($group){
				return $fail('您已开团当前商品！');
			}elseif($user->grade == 'vip'){

				if(!$user->groupCards()->canUsed()->exists()){

					return $fail('没有开团卡，无法开团！');
				}
				
			} 



			return true;
		};
	}

	

}
